<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="../include/tag.jsp" %>
<%@ taglib prefix="memberForm" uri="http://www.tongxingzhe.cn/memberForm" %>
<%@ page import="com.party.core.model.system.TargetType" %>
<!DOCTYPE html>
<html lang="zh">
<head>
    <title>${activity == null ? '发布' : '编辑'}课程</title>
    <%@include file="../include/commonFile.jsp" %>
    <script src="//api.map.baidu.com/api?v=2.0&ak=2izIwlMmDVH737ms8m4Y8uHsoxtEIR65"></script>
    <link rel="stylesheet" href="${ctx}/css/common/list.css">
    <link rel="stylesheet" href="${ctx}/css/ui/activity/publish_form.css">
    <style type="text/css">
        .add-form-content .form-inner {
            padding: 10px;
        }

        .border {
            border: 1px solid #eee;
            padding-left: 0px;
            padding-right: 0px;
            border-radius: 4px;
        }

        fieldset legend {
            font-size: 18px;
            margin-left: 30px;
        }

        .form-tip {
            float: left;
            margin-right: 10px;
            width: calc(100% - 110px);
        }

        .map-warp .layui-form-select dl {
            max-height: 224px !important;
        }
    </style>
</head>
<body>
<!--头部-->
<%@include file="../include/header.jsp" %>
<div class="index-outside">
    <%@include file="../include/sidebar.jsp" %>
    <!--内容-->
    <section>
        <div class="section-main">
            <!-- 正文请写在这里 -->
            <div class="add-form-content">
                <form id="myForm" class="layui-form mt20" method="post" action="${ctx}/activity/course/courseSave.do">
                    <fieldset class="border mb10">
                        <legend>课程基本信息</legend>
                        <div class="form-inner">
                            <div class="layui-form-item">
                                <label class="layui-form-label">课程名称<span class="f-verify-red">*</span></label>
                                <div class="layui-input-block">
                                    <input type="text" name="title" lay-verify="title" placeholder="课程名称"
                                           class="layui-input form-tip" maxlength="50" autocomplete="off"
                                           value="${activity.title}" style="width: 50%"/>
                                    <input type="hidden" name="id" value="${activity.id}"/>
                                    <div class="layui-form-mid layui-word-aux">最多50字符</div>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">海报<span class="f-verify-red">*</span></label>
                                <div class="cover-content">
                                    <input type="hidden" name="pic" id="pic" lay-verify="pic" value="${activity.pic}"/>
                                    <c:if test="${activity == null || empty activity.pic}">
                                        <span id="cover-img" class="cover-img" style="background-image:url(${ctx}/image/posterImg.png)"></span>
                                    </c:if>
                                    <c:if test="${activity != null && not empty activity.pic}">
                                        <span id="cover-img" class="cover-img" style="background-image:url('${activity.pic}')"></span>
                                    </c:if>
                                    <a class="layui-btn layui-btn-danger" id="sel_pic_img">+添加海报</a>
                                    <div class="form-word-aux">建议尺寸：800x450</div>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">报名截止时间<span class="f-verify-red">*</span></label>
                                <div class="layui-input-block">
                                    <input class="layui-input" name="endDate" lay-verify="endDate" placeholder="报名截止时间"
                                           id="endTime" style="width: 190px; float: left; margin-right: 10px;" readonly
                                           value='<fmt:formatDate value="${activity.endTime}" pattern="yyyy-MM-dd HH:mm" />'
                                    />
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">活动开始时间<span class="f-verify-red">*</span></label>
                                <div class="layui-input-block">
                                    <input class="layui-input" name="startDate" lay-verify="startDate" placeholder="活动开始时间"
                                           id="startTime" style="width: 190px; float: left; margin-right: 10px;" readonly
                                           value='<fmt:formatDate value="${activity.startTime}" pattern="yyyy-MM-dd HH:mm" />'
                                    />
                                </div>
                            </div>
                            <%@include file="./cityAreaMapNew.jsp" %>
                            <div id="mapDiv" class="layui-form-item" style="display: none;">
                                <div class="layui-inline">
                                    <label class="layui-form-label"></label>
                                    <div class="layui-input-inline">
                                        <div id="allmap" style="height: 500px;"></div>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">报名方式<span class="f-verify-red">*</span></label>
                                <div class="layui-input-block">
                                    <input type="radio" name="counterfoilType" lay-verify="counterfoilType" value="1" title="免费" lay-filter="counterfoilType"
                                    ${counterfoil == null || counterfoil.payment == 0 ? 'checked="checked"' : ''}
                                    ${counterfoil.joinNum > 0 ? 'disabled' : ''}
                                    >
                                    <input type="radio" name="counterfoilType" lay-verify="counterfoilType" value="2" title="在线付费" lay-filter="counterfoilType"
                                    ${counterfoil != null && counterfoil.payment > 0 ? 'checked="checked"' : ''}
                                    ${counterfoil.joinNum > 0 ? 'disabled' : ''}
                                    >
                                </div>
                            </div>
                            <div class="layui-form-item" id="inviteCodeDiv" ${empty counterfoil.id || counterfoil.payment == 0 ? 'style="display:none"' : ''}>
                                <div class="layui-inline">
                                    <label class="layui-form-label">金额<span class="f-verify-red">*</span></label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="price" lay-verify="price" class="layui-input" value="${counterfoil.payment}" ${counterfoil.joinNum > 0 ? 'readonly' : ''} />
                                    </div>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-inline">
                                    <label class="layui-form-label">人数限制<span class="f-verify-red">*</span></label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="limitNum" lay-verify="limitNum" class="layui-input" value="${counterfoil.limitNum}"/>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">隐藏报名人员<span class="f-verify-red">*</span></label>
                                <div class="layui-input-block">
                                    <input type="radio" name="joinHidden" value="1" title="是"
                                    ${activity == null || activity.joinHidden == 1 ? 'checked="checked"' : ''}
                                    >
                                    <input type="radio" name="joinHidden" value="0" title="否"
                                    ${activity != null && activity.joinHidden == 0 ? 'checked="checked"' : ''}
                                    >
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">课程描述</label>
                                <div class="layui-input-block">
                                    <input type="text" name="remarks" placeholder="课程描述" class="layui-input"
                                           maxlength="100" value="${activity.remarks}">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">活动详情<span class="f-verify-red">*</span></label>
                                <div class="layui-input-block">
                                    <script id="ueditor1" type="text/plain"></script>
                                    <div style="display: none" id="contentView">${activityDetail.content}</div>
                                    <input type="hidden" name="content" id="content" lay-verify="content"
                                           data-link-ue="ueditor1"/>
                                </div>
                            </div>
                        </div>
                    </fieldset>
                    <fieldset class="border mb10">
                        <legend>课程报名表单</legend>
                        <div class="form-inner">
                            <%@include file="../gatherForm/courseCreateForm.jsp" %>
                            <div class="cl"></div>
                        </div>
                    </fieldset>
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <a href="javascript:void(0)" class="layui-btn layui-btn-danger" lay-submit lay-filter="*">立即提交</a>
                            <a href="${ctx}/activity/course/courseList.do"
                               class="layui-btn layui-btn-primary">取消</a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        <!--底部-->
        <%@include file="../include/footer.jsp" %>

        <div style="display: none" id="create_date_str">
            <fmt:formatDate value="${activity.createDate}" pattern="yyyy-MM-dd HH:mm:ss"/>
        </div>
    </section>
</div>

<script type="text/javascript" src="${ctxStatic}/UEditor/ueditor.config.js"></script>
<script type="text/javascript" src="${ctxStatic}/UEditor/ueditor.all.js"></script>
<script type="text/javascript" src="${ctxStatic}/UEditor/myplugin/uploadCI.js"></script>
<script type="text/javascript" src="${ctxStatic}/UEditor/myplugin/uploadVideo.js"></script>
<!--建议手动加在语言，避免在ie下有时因为加载语言失败导致编辑器加载失败-->
<!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型，比如你在配置项目里配置的是英文，这里加载的中文，那最后就是中文-->
<script type="text/javascript" src="${ctxStatic}/UEditor/lang/zh-cn/zh-cn.js"></script>
<script type="text/javascript" src="${ctx}/script/common/form_cache.js"></script>
<script>
    var ue = UE.getEditor('ueditor1'), form, formcache, freeRadioValue = null;
    txz.initHeader({
        nav: [{
            name: '课程管理',
            href: '${ctx}/activity/course/courseList.do'
        }, {
            name: '${activity == null ? '发布' : '编辑'}课程',
            curr: true
        }],
        btns: [{
            name: '返回',
            icon: 'back',
            href: '${ctx}/activity/course/courseList.do'
        }]
    });
    $(function () {
        layui.use(['form', 'laydate'], function () {
            form = layui.form, laydate = layui.laydate;

            form.on('radio(counterfoilType)', function (data) {
                freeRadioValue = data.value;
                $("#inviteCodeDiv input[type=text]").val("");
                if (freeRadioValue == "2") {
                    $("#inviteCodeDiv").show();
                } else {
                    $("#inviteCodeDiv").hide();
                }
            });

            //自定义验证规则
            form.verify({
                title: function (value) {
                    if (value == "") {
                        return '请填写课程标题';
                    }
                },
                pic: function (value) {
                    if (value == "") {
                        return "请上传活动海报";
                    }
                },
                startDate: function (value) {
                    if (value == "") {
                        return "请设置活动开始时间";
                    }

                    if (util.getTimeMillis(value) < util.getTimeMillis()) {
                        return "活动开始时间不得早于当前时间"
                    }
                },
                endDate: function (value) {
                    if (value == "") {
                        return "请设置报名截止时间";
                    }

                    if (util.getTimeMillis(value) < util.getTimeMillis()) {
                        return "截止时间不得早于当前时间";
                    }

                    var startDate = $("[name=startDate]").val();
                    if (value >= startDate) {
                        return "报名截止时间应该早于活动开始时间";
                    }
                },
                counterfoilType: function (value) {
                    var type = $("[name=counterfoilType]:checked").val();
                    if (!util.isValid(type)) {
                        return "请选择报名方式";
                    }
                },
                limitNum: function (value) {
                    if (value == "") {
                        return "请设置活动人数上限";
                    } else if (!util.checkNumber(value)) {
                        return "请输入正确的数字";
                    } else if (parseInt(value) == 0) {
                        return "请输入大于0的数字";
                    }
                },
                price: function (value) {
                    var reg = /^(([0-9]|([1-9][0-9]{0,9}))((\.[0-9]{1,2})?))$/;
                    var type = $("[name=counterfoilType]:checked").val();
                    if (type == "2") {
                        if (value == "") {
                            return "请设置活动报名金额";
                        } else if(parseFloat(value) == 0) {
                            return "金额不能为0";
                        } else if (!reg.test(value)) {
                            return "请输入正确的金额";
                        }
                    }
                },
                content: function () {
                    $("#contentView").html(ue.getContent());
                    var content = $("#contentView").html();
                    if (content == "") {
                        return "请填写活动详情";
                    }
                }
            });

            form.render('radio');
            form.render('checkbox');
            form.render('select');

            //监听提交
            form.on('submit', function (data) {
                submitForm(data);
            });

            function submitForm(data) {
                txz.submitObject(data.elem, function (callBack) {
                    resetFormIndex();
                    var action = $("#myForm").attr("action");
                    var formData = getFormData();
                    txz.ajaxRequest({
                        method: 'post',
                        url: action,
                        saveCache: true,
                        cacheObj: formcache,
                        params: formData,
                        callBack: function (res) {
                            typeof callBack === 'function' && callBack();
                            if (res.success) {
                                util.layerMsgSuccess("提交成功", function () {
                                    location.href = "${ctx}/activity/course/courseList.do";
                                })
                            } else {
                                util.layerMsgError("提交失败")
                            }
                        }
                    });
                });
            }

            var min;
            if (${empty activity.id}) {
                min = new Date().Format('yyyy-MM-dd HH:mm:ss');
            } else {
                min = $("#create_date_str").text();
            }

            //日期
            var start = {
                elem: '#startTime',
                min: min,
                max: '2099-06-16 23:59',
                type: 'datetime',
                format: 'yyyy-MM-dd HH:mm'
            };

            var end = {
                elem: '#endTime',
                min: min,
                max: '2099-06-16 23:59',
                type: 'datetime',
                format: 'yyyy-MM-dd HH:mm' //日期格式
            };
            laydate.render(start);
            laydate.render(end);

            //初始化地图控件
            txz.Map.init({
                layForm: form,
                data: {
                    cityId: '${activity.cityId}',
                    areaInput: '${activity.area}',
                    place: '${activity.place}',
                    cityName: '${cityName}',
                    lat: '${activity.lat}',
                    lng: '${activity.lng}'
                }
            });
            txz.saveStatus = false;
        });
        ue.addListener('ready', function () {
            this.setHeight(500);
            if ($("#contentView").html() != "") {
                this.setHeight(850);
            }
            this.setContent($("#contentView").html());
            //等待ueditor加载完后加载缓存
            if (!'${activity.id}') {
                formcache = new fCache({
                    fCacheKey: 'form_cache_act',//暂存的key
                    cacheCallback: loadCacheData,//获取到缓存后加载的方法
                    getFormData: getFormData
                }).init();
            }
        });

        ue.addListener('blur', function () {
            $("#contentView").html(ue.getContent());
        });

        $('#sel_pic_img').click(function () {
            txz.openSelImg({
                min: 1,
                max: 1,
                info: '建议尺寸：800x450',
                type: '<%=TargetType.COURSE.getCode()%>',
                cb: function (imgs) {
                    $('#cover-img').css('background-image', 'url(' + imgs[0].path + ')');
                    $('#pic').val(imgs[0].path);
                }
            })
        })
    })

    function getFormData() {
        $("#content").val(ue.getContent().replace(/&quot;/gi, ""));
        var formData = util.serializeForm($('#myForm').serializeArray());
        return formData;
    }

    //此方法用于加载缓存数据
    function loadCacheData(cacheData) {
        //是否收费
        if (cacheData['counterfoilType']) {
            freeRadioValue = cacheData['counterfoilType'];
            if (freeRadioValue == "2") {
                $("#inviteCodeDiv input[type=text]").val(cacheData['price']);
                $("#inviteCodeDiv").show();
            } else {
                $("#inviteCodeDiv").hide();
                $("#inviteCodeDiv input[type=text]").val("");
            }
        }
        //加载封面图
        if (cacheData['pic']) {
            $('#cover-img').css('background-image', 'url(' + cacheData['pic'] + ')');
        }
        form.render();
        txz.Map.init({
            layForm: form,
            data: {
                cityId: cacheData.cityId,
                areaInput: cacheData.areaSelect || cacheData.areaInput,
                place: cacheData.place,
                lat: cacheData.lat,
                lng: cacheData.lng
            }
        });
    }

    // 文本编辑器图片上传
    function uEditorUploadCI(editor) {
        txz.openSelImg({
            min: 1,
            type: '<%=TargetType.COURSE.getCode()%>',
            cb: function (imgs) {
                if (imgs.length) {
                    for (var i = 0, item; i < imgs.length; i++) {
                        item = imgs[i];
                        editor.focus();
                        editor.execCommand('inserthtml', item.htmlStr);
                    }
                }
            }
        })
    }

    function uEditorUploadCIVideo(editor) {
        txz.openSelVideo({
            min: 1,
            type: '<%=TargetType.COURSE.getCode()%>',
            cb: function (imgs) {
                if (imgs.length) {
                    for (var i = 0, item; i < imgs.length; i++) {
                        item = imgs[i];
                        editor.focus();
                        editor.execCommand('inserthtml', item.htmlStr);
                    }
                }
            }
        })
    }
</script>
</body>
</html>